
import { get, post } from "./request"

let limitUpload = false;//节流防止被频繁调用
let reLogin = false;//标记是否需要重新登录
let reLoginTime = 0;
/**
 * 上传步数, showOnce为true时只弹窗打开微信运动一次
 * @param uploadSuccessCallback
 * @param showOnce
 */
export function uploadSteps(uploadSuccessCallback, showOnce=false) {
  // 取消关注微信运动后不上再上传步数,防止持续弹窗
  if (global.weSportsCancel === true && !showOnce) {
    return Promise.reject(false)
  }
  //限制1s内只上传一次步数
  if(limitUpload) return Promise.resolve(true)
  limitUpload = true;
  return new Promise(function (resolve, reject) {
    wx.getWeRunData({
      success: (r) => {
        //步数授权成功
        global.weRunStatus = 1;
        global.weSportsCancel = false
        resolve(true);
        //体验账号 不上传步数
        if (!global.experience) {
          post('/sport-rest/weixin/uploadStep', {
            encryptedData: r.encryptedData,
            iv: r.iv
          }).then(res => {
            uploadSuccessCallback && uploadSuccessCallback();
            setTimeout(() => {
              limitUpload = false;
            }, 1000);
            if (res.data && res.data.code === 500) {
              //重新登录
              reLogin = true;
            }
          }).catch(err => {
            reLogin = true;
            limitUpload = false;
          })
        }
      },
      fail: (err) => {
        if ((err.errMsg.indexOf('cancel') > -1) && (global.weSportsCancel !== true)) {
          global.weSportsCancel = true; // 微信运动公众号已取消
          wx.showModal({
            content: '若不启用微信运动。未来启用后，须移除小程序后重新打开进行授权。',
            confirmText: '我知道了',
            showCancel: false
          })

        }
        global.weRunStatus = 2;
        limitUpload = false;
        reject(false);
      }
    })
  });
}

// function wxLogin() {
//   if (global.loginInfo) {
//     Promise.resolve(res.code)
//   }
//   wx.login({
//     success(res) {

//     }
//   })
// }

function AuthLoginByWeixin(params) {
  return post('/sessions-rest/loginByThirdParty', params, { withRequestToken: true });
}


let innerWxLogin = function (userInfo, iv, encryptedData, param = {}) {
  userInfo && wx.showLoading({
      mask: true,
      icon: 'loading',
      title: '登录...'
  });
  return new Promise(function (resolve, reject) {
      wx.login({
          success(res) {
              global.loginCode = res.code;
              iv && (global.loginInfo = { iv, encryptedData }); // 存储个人信息加密内容用于unionid上传
              if (!global.loginInfo) {
                global.loginInfo = { }
              }
              let params = Object.assign({ isLogin: true, code: res.code, openAccountType: 1, appId: 'wxd2b006129f68348d', tenantId: 195, subscriptionId: 19501, iv: global.loginInfo.iv, encryptedData: global.loginInfo.encryptedData }, param);
              AuthLoginByWeixin(params).then(resp => {
                  if (resp.code === 200) {
                      resolve(resp);
                  } else {
                      wx.hideLoading();
                      reject(resp);
                  }
              }).catch((err) => {
                  wx.hideLoading();
                  reject(err);
              });
          },
          fail(res) {
              reject(res);
          }
      });
  });
};
